<template>
  <div class="backStack-side-menu-wrap">
    <div class="side-menu-body-wrap">
      <a-menu
        style="width: 100%"
        :selectedKeys="current"
        :openKeys.sync="current"
        mode="inline"
        @click="handleClick"
      >
        <template v-for="sub in sideMenus">
          <a-sub-menu :key="sub.title" v-if="sub.child">
            <span slot="title">
              <span :class="{ titleActived: titleActieved(sub.title) }">{{
                sub.title
              }}</span>
            </span>
            <template v-for="item in sub.child">
              <a-sub-menu :key="item.key" v-if="item.child">
                <span slot="title">
                  <span :class="{ titleActived: titleActieved(sub.title) }">{{
                    item.name
                  }}</span>
                </span>
                <a-menu-item v-for="i in item.child" :key="i.key">
                  {{ i.name }}
                </a-menu-item>
              </a-sub-menu>
              <a-menu-item v-else :key="item.key">
                {{ item.name }}
              </a-menu-item>
            </template>
          </a-sub-menu>
          <a-menu-item v-else :key="sub.key">
            {{ sub.title }}
          </a-menu-item>
        </template>
      </a-menu>
    </div>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
import { mapGetters } from 'vuex'
import { sideOptions, nameMap } from './configs'

export default {
  props: {
    sideOpen: Array
  },
  data() {
    return {
      sideOptions,
      current: []
    }
  },
  components: {},
  computed: {
    ...mapGetters('user', ['account', 'role']),
    sideMenus() {
      let list = []
      const userList = [
        '账户信息',
        '开放许可管理',
        '需求管理',
        '运营管理',
        '服务机构',
        '收藏管理'
      ]
      const copyList = cloneDeep(this.sideOptions)
      switch (this.role) {
        case 'admin':
        case 'bus':
          list = copyList
          break
        case 'user':
          copyList.forEach(option => {
            if (userList.indexOf(option.title) >= 0) {
              list.push({
                title: option.title,
                child: option.child
              })
            }
          })
          break
        default:
          list = []
          break
      }
      return list
    }
  },
  watch: {
    $route(to) {
      const { key } = to.query
      this.setCurrentKeys(key)
    }
  },
  mounted() {
    const { key } = this.$route.query
    this.setCurrentKeys(key)
  },
  methods: {
    setCurrentKeys(key) {
      if (!key) return
      const parent = nameMap[key]
      this.current = parent ? [parent, key] : [key]  //兼容没有二级菜单的菜单项
    },
    handleClick(e) {
      const { key, keyPath } = e
      const name = key
      const meta = keyPath[1]
      this.current = keyPath
      this.$emit('sideMenuClick', { name, meta })
    },
    titleActieved(key) {
      return this.current.includes(key)
    }
  }
}
</script>
